package edu.msg.jthr.web.servlets;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.msg.jthr.backend.exception.ServiceException;
import edu.msg.jthr.backend.model.Department;
import edu.msg.jthr.backend.model.Job;
import edu.msg.jthr.backend.model.JobDescription;
import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.DepartmentService;
import edu.msg.jthr.backend.service.JobService;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.web.util.RoleAssembler;

/**
 * Servlet implementation class AddJob
 */
@WebServlet("/AddJob")
public class AddJob extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final Logger LOG = LoggerFactory
			.getLogger(AddJob.class);
	@EJB
	private JobService jobService;
	@EJB
	private DepartmentService departmentService;
	@EJB
	private UserService userService;
	private HttpSession session;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddJob() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		User user = (User) session.getAttribute("activeUser");
		if (user == null) {
			user = userService.getUserByUserName(request.getUserPrincipal()
					.toString());
			String role = RoleAssembler.getRole(user.getUserGroups());
			session.setAttribute("role", role);
			session.setAttribute("activeUser", user);
		}
		List<Department> departmentList = new ArrayList<Department>();
		try {
			departmentList = departmentService.getAll();
		} catch (ServiceException ex) {
			LOG.error("Failure by userBeans setting!", ex);
		}
		session.setAttribute("departmentList", departmentList);
		request.getRequestDispatcher("/pages/AddJob.jsp").forward(request,
				response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		session = req.getSession(true);
		Job job = new Job();
		User proposer = (User) session.getAttribute("activeUser");
		Department department = new Department();
		String departmentString = req.getParameter("selection");
		try {
			department = departmentService.getById(Long
					.parseLong(departmentString));
			System.out.println(department.getName());
		} catch (ServiceException e) {
			LOG.error("Conversion failed from string to Long", e);
		}
		JobDescription jobDescription = new JobDescription();
		jobDescription.setDepartment(department);
		jobDescription.setProject(req.getParameter("project"));
		jobDescription.setRequirements(req.getParameter("requirements"));
		jobDescription
				.setResponsabilities(req.getParameter("responsabilities"));

		job.setTitle(req.getParameter("title"));
		job.setProposer(proposer);
		job.setOpened(true);
		job.setApproved(Boolean.valueOf(req.getParameter("approved")));
		job.setMaxCandidates(Integer.parseInt(req.getParameter("candidates")));
		job.setDescription(jobDescription);
		try {
			String dateString = req.getParameter("date");
			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date date;
			date = formatter.parse(dateString);
			job.setDeadLine(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		List<Job> jobList = Collections.emptyList();
		try {
			jobService.create(job);
			jobList = jobService.getAll();
		} catch (ServiceException e) {
			LOG.error(e.getMessage());
		}
		session.setAttribute("jobList", jobList);
		req.getRequestDispatcher("/pages/ShowJobs.jsp").forward(req, response);
	}
}
